#!/usr/local/bin/php
<?php
defined('OPEN_LIB_PATH') || define('OPEN_LIB_PATH', '/opt/op/OpenLib');

require_once OPEN_LIB_PATH . '/open/models/OaAppModel.php';

$logger = Log::factory('console', '', '', array(
    'lineFormat' => '[%1$s] [%3$s] %5$s(%6$s): %4$s',
    'timeFormat' => '%Y-%m-%d %H:%M:%S'
), PEAR_LOG_INFO);
$logger->setPriority(PEAR_LOG_INFO);

$options = getopt('c:a:n:m:j:');
if (empty($options)) {
    $logger->err("usage: " . basename(__FILE__) . " -c company_id -a app_id -n app_name -m admin [-j join_type]");
    exit();
}
if (!isset($options['c'])) {
    $logger->err("no company id");
    exit();
}
$companyId = (int) $options['c'];
if ($companyId <= 0) {
    $logger->err("company id invalid: company-$companyId");
    exit();
}
if (!isset($options['a'])) {
    $logger->err("no app id");
    exit();
}
$appId = (int) $options['a'];
if ($appId <= 0) {
    $logger->err("app id invalid: app-$appId");
    exit();
}
if (!isset($options['n'])) {
    $logger->err("no app name");
    exit();
}
$appName = $options['n'];
if (!isset($options['m'])) {
    $logger->err("no admin");
    exit();
}
$admin = $options['m'];
if (isset($options['j'])) {
    $joinType = (int) $options['j'];
} else {
    $joinType = OaAppModel::APP_JOIN_FLOW_CUSTOMIZE;
}

$appModel = new OaAppModel(OaAppModel::APP_CONFIG_ENV_PRODUCTION, $logger);
$appId = $appModel->createApp($appName, $admin, $companyId, array(
    'id' => $appId,
    'join_type' => $joinType
));
if ($appId == false) {
    $logger->err("create app failed: error-" . $appModel->getErrorMessage());
} else {
    $logger->info("create app succeed: app-$appId");
}
